import * as React from 'react';
import { useState, useEffect, FC, CSSProperties, useMemo, useRef } from 'react';
import { useInterval } from 'ahooks';
import './index.less';

interface SwiperItmeProps {
  /** 数据  */
  dataList: any[];
  /** col span  */
  span: number;
  /** 滑到最后多少列重置  */
  endNumbe?: number;
  /** 速度 ms  */
  speed?: number;
}

const SwiperItme: FC<SwiperItmeProps> = props => {
  const { children, dataList, span, endNumbe, speed } = props;
  const [translateY, settranslateY] = useState<number>(0);
  const itemRef = useRef<HTMLDivElement>(null);
  const swiperRef = useRef<HTMLDivElement>(null);
  const [clientHeight, setclientHeight] = useState<number>(0);
  /**
   * @description: 计算css样式
   * @param {*}
   * @return {*}
   */
  const itemStyle: CSSProperties = useMemo(() => {
    return {
      transform: `translateY(${translateY}px)`,
      transitionDuration: `${speed}ms`,
    };
  }, [translateY]);
  /**
   * @description: 计算每个子div的高度
   * @param {*}
   * @return {*}
   */
  const oneHeight = useMemo(() => {
    if (clientHeight) {
      return clientHeight / Math.ceil(dataList.length / Math.floor(24 / span));
    }
  }, [dataList, span, clientHeight]);
  /**
   * @description: 获取总高
   * @param {*}
   * @return {*}
   */
  useEffect(() => {
    const { current } = itemRef;
    if (itemRef && current && dataList && dataList.length > 0) {
      setclientHeight(current.clientHeight);
    }
  }, [dataList]);
  /**
   * @description: 设置偏移量
   * @param {*}
   * @return {*}
   */
  useInterval(() => {
    if (oneHeight) {
      settranslateY((r: number) => {
        if (Math.abs(r) + oneHeight * (endNumbe || 4) > clientHeight) {
          return 0;
        } else {
          return r - oneHeight;
        }
      });
    }
  }, 1000);
  const allNumber = useMemo(() => {
    if (swiperRef && swiperRef.current && oneHeight && oneHeight > 0) {
      return Math.floor(swiperRef.current.clientHeight % oneHeight);
    }
  }, [swiperRef, oneHeight]);

  return (
    <div className="c-swiper" ref={swiperRef}>
      <div className="c-swiper-itme" ref={itemRef} style={itemStyle}>
        {children}
      </div>
    </div>
  );
};
SwiperItme.defaultProps = {
  endNumbe: 4,
  speed: 300,
};
export default SwiperItme;
